package com.synjones.handsetS8.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.format.Time;
import android.text.style.ForegroundColorSpan;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by zhaodianbo on 2016-3-9.
 */
public class myTools {


    public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."+
                    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
                    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
                    "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }

    public static SpannableStringBuilder getRedText(String text){
        return getColorText(text, Color.RED);
    }
    public static SpannableStringBuilder getColorText(String text,int color){
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色 Color.RED
        ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
        builder.setSpan(redSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

   public static boolean makeFolderIfNotExists(String strFolder) {
        try{
            File file = new File(strFolder);
            if (!file.exists())
            {
                if (file.mkdirs())
                    return true;
                else
                    return false;
            }

        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            stringBuilder.append("0x");
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            stringBuilder.append(hv.toUpperCase());
            stringBuilder.append(",");
        }
        return stringBuilder.toString();
    }

    public static byte[] hexString2bytes(String src){
        try{
            if(src==null||src.length()==0) return null;
            int srcLen=src.length();
            if(srcLen%2!=0) {
                src += "0";
                srcLen++;
            }
            byte ret[]=new byte[srcLen/2];
            for(int i=0,j=0;i<=srcLen-2;i+=2,j++){
                String hex=src.substring(i,i+2);
                ret[j]=(byte)Integer.parseInt(hex,16);
            }
            return ret;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String bytesToHexStringNo0x(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);

            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            stringBuilder.append(hv.toUpperCase());
            // stringBuilder.append(" ");
        }
        return stringBuilder.toString();
    }

    public static String bytesToHexStringNo0x(byte[] src,int len){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <len) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);

            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            stringBuilder.append(hv.toUpperCase());
            // stringBuilder.append(" ");
        }
        return stringBuilder.toString();
    }


    public static String bytesToHexString(byte[] src,int len){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        if(src.length<len) return null;
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            stringBuilder.append("0x");
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            stringBuilder.append(hv.toUpperCase());
            stringBuilder.append(",");
        }
        return stringBuilder.toString();
    }


    public static String getVersionName(Context ctx)
    {
        // 获取packagemanager的实例
        PackageManager packageManager = ctx.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        String version="未知";
        try {
            packInfo = packageManager.getPackageInfo(ctx.getPackageName(),0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return version;
    }

    public static int getVersionCode(Context ctx)
    {
        // 获取packagemanager的实例
        PackageManager packageManager = ctx.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        int version=0;
        try {
            packInfo = packageManager.getPackageInfo(ctx.getPackageName(),0);
            version = packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return version;
    }

    public static void installAPK(Context context, File file) {
        if (file == null || !file.exists())
            return;
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    private static final boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static final boolean haveChineseChar(String str) {
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    public static void sleep(long t){
        try{
            Thread.sleep(t);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String getToday() {
        try {
            Time mytoday = new Time();
            mytoday.setToNow();
            return mytoday.format("%Y-%m-%d");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getNow() {
        try {
            Time mytoday = new Time();
            mytoday.setToNow();
            return mytoday.format("%H:%M:%S");
        } catch (Exception e) {
            e.printStackTrace();

            return "";
        }
    }
    public static String getDate() {

        try {
            Time mytoday = new Time();
            mytoday.setToNow();
            return  mytoday.format("%Y-%m-%d %H:%M:%S");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getDateNoBlank() {

        try {
            Time mytoday = new Time();
            mytoday.setToNow();
            return  mytoday.format("%Y%m%d-%H%M%S");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static long getDateDayDiff(String date1,String date2)throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time1 = sdf.parse(date1);
        Date time2 = sdf.parse(date2);
        long diffMss=time1.getTime()-time2.getTime();
        diffMss=Math.abs(diffMss);
        return diffMss/(1000*60*60*24);
    }





    public static void fixOrientation(Activity act){
        if (act.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        else
        {
            act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    public static  String ExternalPath=null;

    public  static boolean inti_util_File(){
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
        {
            ExternalPath=getExternalPath();
        }
        else
        {
            return false;
        }

        return ExternalPath == null ? false:true;
    }
    public static String getExternalPath(){
        try {
            ExternalPath=Environment.getExternalStorageDirectory().getCanonicalPath()+"/";
            return ExternalPath;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static boolean fileIsExists(String filename){
        try{
            File f=new File(filename);
            if(!f.exists()){
                return false;
            }

        }catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }
    public static boolean writeStr2SdcardFile(String fileName,String write_str){
        boolean ret=false;
        try{
            FileOutputStream fout = new FileOutputStream(fileName);
            byte [] bytes = write_str.getBytes();
            fout.write(bytes);
            fout.close();
            ret=true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ret;

    }
    public static boolean writeByte2SdcardFile(String fileName,byte write_byte[]){
        boolean ret=false;
        try{
            FileOutputStream fout = new FileOutputStream(fileName);
            fout.write(write_byte);
            fout.flush();
            fout.close();
            ret=true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    public static boolean appendByte2SdcardFile(String fileName,byte write_byte[]){
        boolean ret=false;
        try{
            FileOutputStream fout = new FileOutputStream(fileName,true);
            // byte [] bytes = write_str.getBytes();
            fout.write(write_byte);
            fout.flush();
            fout.close();
            ret=true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ret;

    }

    public static byte [] readAllSdcardFile(String fileName){
        // String res="";
        byte [] buffer = null;

        try{
            FileInputStream fin = new FileInputStream(fileName);
            int length = fin.available();
            buffer = new byte[length];
            fin.read(buffer);
            fin.close();
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
        return buffer;
    }

    public static boolean copyfile(String src, String des){
        boolean ret=false;
        try{
            FileInputStream fin = new FileInputStream(src);
            FileOutputStream fout = new FileOutputStream(des);
            int length=0;
            byte[] buffer = new byte[2048];
            while((length=fin.read(buffer))>0)
                fout.write(buffer,0,length);
            fin.close();
            fout.flush();
            fout.close();
            ret=true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    public interface ProgressCallBack{
        boolean onProgress(int progress, int total);
    }


    public static boolean copyfileWithProgress(String src, String des,ProgressCallBack progressCallBack){
        boolean ret=false;
        try{
            FileInputStream fin = new FileInputStream(src);
            FileOutputStream fout = new FileOutputStream(des);
            int length=0;
            int total=fin.available();
            int progress=0;
            boolean stop=false;
            byte[] buffer = new byte[2048];
            while((length=fin.read(buffer))>0) {
                fout.write(buffer, 0, length);
                if(length>0 && progressCallBack!=null) {
                    progress += length;
                    if(!progressCallBack.onProgress(progress, total)) {
                        stop = true;
                        break;
                    }
                }
            }
            fin.close();
            fout.flush();
            fout.close();
            if(stop){
                deleteIfExists(des);
            }else
                ret=true;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    public	static boolean isFolderExists(String strFolder) {
        try{
            File file = new File(strFolder);
            if (!file.exists())
            {
                if (file.mkdirs())
                    return true;
                else
                    return false;
            }

        }catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    public	static void deleteIfExists(String filepath) {
        try{
            File file = new File(filepath);
            if (file.exists())
            {
                file.delete();
            }
        }catch (Exception e) {
        }
    }

    public static boolean rename(String oldpath,String newpath){
        File file=new File(oldpath);
        return file.renameTo(new File(newpath));
    }

    /**
     *
     * @param mss 要转换的毫秒数
     * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
     * @author fy.zhang
     */
    public static String formatDuringm(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        if(hours>0)
            return String.format("%d:%02d:%02d.%03d",hours,minutes,seconds,mss%1000);
        if(minutes>0)
            return String.format("%d:%02d.%03d",minutes,seconds,mss%1000);
        return String.format("%d.%03d",seconds,mss%1000);
			/*return days + " days " + hours + ":" + minutes + ":"
					+ seconds + "";*/
    }



}
